class Solution
{
public:
    int firstCompleteIndex(vector<int> &arr, vector<vector<int>> &mat)
    {
        int m = mat.size();
        int n = mat[0].size();
        vector<int> rowCount(m, 0);
        vector<int> colCount(n, 0);
        vector<array<int, 2>> coordinateMap(m * n + 1);
        for (int i = 0; i < m; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                coordinateMap[mat[i][j]] = {i, j};
            }
        }
        for (int i = 0; i < m * n; ++i)
        {
            int num = arr[i];
            auto [row, col] = coordinateMap[num];
            ++rowCount[row];
            ++colCount[col];
            if (rowCount[row] == n || colCount[col] == m)
            {
                return i;
            }
        }
        return -1;
    }
};